package controllers

import (
	"github.com/gin-gonic/gin"
	"shop/model"
	"shop/pkg/result"
	"shop/services"
)

func GetUserFromContext(c *gin.Context) model.User {
	u := model.User{}
	if id, exists := c.Get("userId"); exists {
		if v, ok := id.(int64); ok {
			u.ID = v
		}
	}
	if name, exists := c.Get("userName"); exists {
		if v, ok := name.(string); ok {
			u.Username = v
		}
	}
	return u
}

// Login 登录
func Login(c *gin.Context) {
	r := result.Create(c)
	var u model.User
	c.ShouldBindJSON(&u)
	data, _ := services.Login(u.Username, u.Password)
	r.Success(data)
}

// GetUserMsg 用户获取个人信息
func GetUserMsg(c *gin.Context) {
	r := result.Create(c)
	user := GetUserFromContext(c)
	data := services.GetById(user.ID)
	r.Success(data)
}

// Register 注册
func Register(c *gin.Context) {
	r := result.Create(c)
	var u model.User
	c.ShouldBindJSON(&u)
	services.Add(u)
	r.Success(nil)
}

// CanCel 注销
func CanCel(c *gin.Context) {
	r := result.Create(c)
	user := GetUserFromContext(c)
	services.DeleteById(user.ID)
	r.Success(nil)
}
